package cn.codeartist.springboot.component.context;

import lombok.AllArgsConstructor;
import lombok.Getter;
import org.springframework.context.ApplicationContextException;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;

/**
 * 环境抽象工具
 *
 * @author 艾江南
 * @date 2019/5/30
 */
public class Environments implements EnvironmentAware {

    private static Environment environment;

    /**
     * 是否为开发环境
     */
    public static boolean isDev() {
        EnvironmentEnum env = EnvironmentEnum.of(getEnvironment());
        return EnvironmentEnum.DEV.getGroup().equals(env.getGroup());
    }

    /**
     * 是否为测试环境
     */
    public static boolean isTest() {
        EnvironmentEnum env = EnvironmentEnum.of(getEnvironment());
        return EnvironmentEnum.TEST.getGroup().equals(env.getGroup());
    }

    /**
     * 是否为生产环境
     */
    public static boolean isProd() {
        EnvironmentEnum env = EnvironmentEnum.of(getEnvironment());
        return EnvironmentEnum.PROD.getGroup().equals(env.getGroup());
    }

    private static String getEnvironment() {
        String[] activeProfiles = environment.getActiveProfiles();
        if (activeProfiles.length > 0) return activeProfiles[0];
        throw new ApplicationContextException("No active profile");
    }

    @Override
    public void setEnvironment(Environment environment) {
        Environments.environment = environment;
    }

    @Getter
    @AllArgsConstructor
    public enum EnvironmentEnum {

        /**
         * 本地、开发、测试、生产
         */
        LOCAL("local", "dev"),
        DEV("dev", "dev"),
        TEST("test", "test"),
        STG("stg", "prod"),
        PROD("prod", "prod");

        private final String env;
        private final String group;

        public static EnvironmentEnum of(String env) {
            for (EnvironmentEnum val : values()) {
                if (val.env.equals(env)) {
                    return val;
                }
            }
            throw new ApplicationContextException("No environment enum: " + env);
        }
    }
}
